<script setup>
import { onMounted, ref, defineProps } from 'vue'
import { useRouter } from 'vue-router'
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'

const router = useRouter()
const pathId = ref(router.currentRoute.value.query.id)
const title = ref('')

const props = defineProps({
  loginForm: {
    type: Object,
    default: () => ({
      phone: '',
      password: '',
    }),
  },
})

const emit = defineEmits(['signUp'])

const formData = ref({
  phone: props.loginForm.phone,
  code: '',
})
const formRef = ref(null)
// 表单验证
const validatePhone = (rule, value, callback) => {
  const phoneRegex = /^1[3-9]\d{9}$/

  if (!phoneRegex.test(value)) {
    callback(new Error('请输入有效的手机号'))
  } else {
    callback()
  }
}

const FormRules = ref({
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    {
      validator: validatePhone,
      trigger: 'blur',
    },
  ],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
})

onMounted(() => {
  title.value = pathId.value === 'register' ? '注册' : '忘记密码'
})

const sendCodeMessage = ref('发送验证码')
const codeTime = ref(60)
let timer = null

const sendCode = () => {
  if (timer) return // 防止重复点击
  sendCodeMessage.value = `${codeTime.value}秒后重新发送`

  timer = setInterval(() => {
    if (codeTime.value > 0) {
      codeTime.value--
      sendCodeMessage.value = `${codeTime.value}秒后重新发送`
    } else {
      clearInterval(timer)
      timer = null
      codeTime.value = 60
      sendCodeMessage.value = '发送验证码'
    }
  }, 1000)
}

const nextStep = () => {
  // TODO: 校验验证码

  // 跳转到设置密码页面
  formRef.value.validate(async (valid) => {
    if (valid) {
      emit('signUp', { phone: formData.value.phone })
      router.push({ path: `/login/setpassword`, query: { id: pathId.value } })
      ElNotification({
        title: '提示',
        message: '验证成功',
        type: 'success',
        duration: 1500,
      })
    } else {
      ElNotification({
        title: '提示',
        message: '验证失败',
        type: 'error',
        duration: 1500,
      })
    }
  })
}
</script>

<template>
  <div class="sign-up">
    <div class="header">
      <img class="logo" src="/public/images/logo.png" alt="" />
      <h1 class="title">{{ title }}</h1>
    </div>
    <div class="content">
      <el-form :model="formData" :rules="FormRules" ref="formRef" class="data-form">
        <el-form-item class="form-item" prop="phone">
          <label>电话号码</label>
          <el-input
            v-model="formData.phone"
            placeholder="输入电话"
            class="custom-input"
            :prefix-icon="UserFilled"
          >
          </el-input>
        </el-form-item>
        <el-form-item class="form-item" prop="code">
          <label>验证码</label>
          <el-input
            v-model="formData.code"
            placeholder="输入验证码"
            class="custom-input"
            :prefix-icon="Lock"
          >
            <template #append>
              <el-button type="primary" class="send-code-btn" @click="sendCode">{{
                sendCodeMessage
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-button type="primary" class="signin-btn" @click="nextStep">下 一 步</el-button>
      </el-form>
    </div>
    <div class="footer">
      <div class="footer-content">
        <div class="footer-item">
          <router-link to="/login">已有账号，去登录</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.sign-up {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  /* 让 logo 靠左，标题居中 */
  .header {
    position: relative;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .logo {
      width: 100px;
    }

    .title {
      position: absolute;
      left: 50%;
      font-size: 24px;
      font-weight: bold;
      transform: translate(-50%);
    }
  }

  .content {
    width: 100%;
    padding: 10px;

    .data-form {
      .form-item {
        margin-bottom: 24px;

        label {
          display: block;
          margin-bottom: 8px;
          color: #000000;
          font-size: 16px;
        }

        .custom-input {
          :deep(.el-input__wrapper) {
            padding: 10px;
            font-size: medium;
          }
        }

        .send-code-btn {
          width: 130px;
          color: #000;
        }
      }
      .signin-btn {
        width: 100%;
        height: 40px;
        margin-top: 10px;
        border-radius: 6px;
        font-size: medium;
      }
    }
  }
  .footer {
    .footer-content {
      .footer-item {
        margin-top: 10px;
        text-align: center;
        a {
          color: #409eff;
          font-size: 14px;

          &:hover {
            text-decoration: underline;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
